#include "columnlabel.h"
#include <allegro5/allegro5.h>
#include <allegro5/allegro_primitives.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include "font.h"
#include "event.h"
using namespace std;

const int ColumnLabel::SeparatorThickness = 1;

ColumnLabel::ColumnLabel(int count, Font *pFont, Point start, int width)
: m_count(count), m_pFont(pFont), m_start(start), 
  m_width(width), m_offset(0) {
}

void ColumnLabel::setCount(int count) {
     m_count = count;
}

void ColumnLabel::setOffset(int offset) {
     m_offset = offset;
}

void ColumnLabel::setStart(Point start) {
     m_start = start;
}

void ColumnLabel::setWidth(int width) {
     m_width = width;
}

Rect ColumnLabel::rect() {
     int h = m_pFont->height() + ColumnLabel::SeparatorThickness;
     return Rect(m_start.x(), m_start.y(), m_width, h);
}

void ColumnLabel::paint() {
     Rect r = rect();
     int thick = ColumnLabel::SeparatorThickness;
     int colwidth = Event::strlen * m_pFont->width() + thick + 2;
     int viscols = ceil((float)r.width() / (float)colwidth);
     r.setHeight(m_pFont->height());
     int linex = 0;
     ostringstream s;
     Rect lr = r;
     lr.setX(lr.x() + thick + 3);
     int i;
     for (i=0; i<viscols && i+m_offset<m_count; i++) {
	  linex = r.x() + i * colwidth;
	  al_draw_line(linex, r.y(), linex, r.y() + r.height() - 1 - thick, 
		       al_map_rgb(255,255,255), thick);
	  s.str("");
	  s << m_offset+i+1;
	  if (lr.x() + lr.width() > m_start.x() + m_width)
	       lr.setWidth(m_start.x() + m_width - lr.x());
	  m_pFont->print(s.str(), lr);
	  lr.setX(lr.x() + colwidth);
     }
     linex = r.x() + i * colwidth;
     al_draw_line(linex, r.y(), linex, r.y() + r.height() - 1 - thick, 
		  al_map_rgb(255,255,255), thick);
     int liney = r.y() + r.height();
     al_draw_line(r.x(), liney, r.x() + r.width(), liney, 
		  al_map_rgb(255,255,255), thick);
}
